package com.shuiyun.cloud.controller;


import com.shuiyun.cloud.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author zhoujiwei
 * @create 2018/7/5 9:43
 * @desc
 **/
@Slf4j
@RequestMapping("/management/apps")
@RestController
public class ApplicationController {

    public static final String HTTP = "http://";
    public static final String LOCALHOST = "localhost:";
    public static final String EUREKA_APPS = "/eureka/apps/";
    public static final String DASH = "/";
    public static final String COMMA = ":";

    @Value("${server.port}")
    private Integer port;

    @Autowired
    private RestTemplate restTemplate;

    @DeleteMapping("/{application}/instance/{instanceId:.+}")
    public Result deleteAppInstance(@PathVariable("application") String application,
                                    @PathVariable("instanceId") String instanceId) {
        String[] str = instanceId.split(COMMA);
        String shutdownUrl = HTTP + str[0] + COMMA + str[1] + DASH + "shutdown";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.postForEntity(shutdownUrl, requestEntity, String.class);
        } catch (Exception e) {
            log.warn("catch exception {}", e.toString());
        }

        String instanceUrl = HTTP + LOCALHOST + port + EUREKA_APPS + application + DASH + instanceId;
        restTemplate.delete(instanceUrl);
        if (response != null && response.getStatusCode() == HttpStatus.OK) {
            return Result.success("移除微服务实例" + application + COMMA + instanceId + "成功");
        }

        return Result.fail("移除微服务实例" + application + COMMA + instanceId + "失败");
    }
}
